package com.dayuanit.dy17.mix.single;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Pig {

    private static Pig pig;
    private static Lock lock = new ReentrantLock();

    private Pig() {

    }

    //此种方式在并发情况下，可能会出现多个小猪对象。
    public static Pig getPig() {
        if (pig == null) {
            pig = new Pig();
        }
        return pig;
    }


    //加锁 保证线程安全 但是在高并发情况下 效率会比较低。
    public synchronized static Pig getPig2() {
        if (pig == null) {
            pig = new Pig();
        }
        return pig;
    }

    public static Pig getPig3() {
        synchronized (Pig.class) {
            if (pig == null) {
                pig = new Pig();
            }
            return pig;
        }
    }

    public static Pig getPig4() {
        lock.lock();
        try {
            if (pig == null) {
                pig = new Pig();
            }
            return pig;
        } finally {
            lock.unlock();
        }
    }
}
